import hashlib
import json, struct
from conf import settings
import os


def get_password(password):
	md5 = hashlib.md5()
	md5.update(password.encode('utf-8'))
	return md5.hexdigest()


def send_back(client, send_dic, file=None):
	"""
	:param client: 连接
	:param send_dic: 发送的内容
	:return: 返回接收到的内容
	"""
	data_bytes = json.dumps(send_dic).encode('utf-8')
	header = struct.pack('i', len(data_bytes))
	client.send(header)
	client.send(data_bytes)
	if file:
		with open(file, 'rb') as f:
			for line in f:
				client.send(line)
	back_header = client.recv(4)
	data_bytes = client.recv(struct.unpack('i', back_header)[0])
	back_dic = json.loads(data_bytes.decode('utf-8'))
	return back_dic


def get_movie_list():
	return os.listdir(settings.BASE_UPLOAD_MOVIE)


def get_movie_md5(movie_name):
	path = os.path.join(settings.BASE_UPLOAD_MOVIE, movie_name)
	file_size = os.path.getsize(path)
	file_index = [0, file_size // 4, file_size // 2, file_size - 10]
	md5 = hashlib.md5()
	with open(path, 'rb') as f:
		for i in file_index:
			f.seek(i)
			md5.update(f.read(10))
		return md5.hexdigest()


if __name__ == '__main__':
	print(get_movie_md5(r"04 设置严格模式.mp4"))

